package com.inoneone.youba.mcht.util;

import sun.misc.BASE64Encoder;
import sun.misc.HexDumpEncoder;

import java.security.MessageDigest;

/**
 * ClassName: MD5 <br/>
 * Function: MD5工具类. <br/>
 * date: 2016年9月5日 下午1:47:28 <br/>
 *
 * @author 姬远玄
 * @since JDK 1.7
 */
public class MD5 {
    private static String UTF8 = "UTF-8";

    public static String encode(String password, String charset) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");

            byte[] result = md5.digest(password.getBytes(charset));

            return bytesToHexString(result);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String encode(String password) {
        return encode(password, UTF8);
    }

    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

}